/**
 * weapp-js
 * https://code.aliyun.com/jionglee/weapp_base.git
 * Copyright@ 2020 Motigo, Inc.
 * 
 */
import session from '../session.js';
import theme from '../theme.js';

Component({
    data: {
        visible: false,
        content_visible: false,
        logo: theme.login.logo,
        title: ''
    },
    callback_success: null,
    callback_fail: null,
    methods: {
        stopEvent() {},
        onCancel() {
            this.setData({
                visible: false
            });

            this.callback_fail && this.callback_fail();
        },
        login(opts) {
            opts;

            wx.getSetting({
                success: res => {
                    // 已经获得鉴权的，直接调用getUserInfo接口
                    if (res.authSetting['scope.userInfo']) {
                        this._getUserInfo(false);
                    } else {
                        this.setData({
                            visible: true,
                            title: opts.title || '请完成微信授权以继续使用'
                        });

                        // 等根节点显示出来下一帧再显示content
                        wx.nextTick(() => {
                            this.setData({
                                content_visible: true
                            });
                        });
                    }
                }
            });

            return new Promise((resolve, reject) => {
                this.callback_success = resolve;
                this.callback_fail = reject;
            });
        },
        // 点击了“登录”
        onLogin(evt) {
            const detail = evt.detail;

            if (detail.errMsg === 'getUserInfo:ok') {
                this._getUserInfo(true);
            } else {
                this.onCancel();
            }
        },
        _getUserInfo(show_loading) {
            show_loading && wx.showLoading({
                title: '登录中...'
            });

            wx.getUserInfo({
                withCredentials: true,
                success: res => {
                    session.decrpytUserInfo(res.encryptedData, res.iv).then(data => {
                        this.setData({
                            content_visible: false,
                            visible: false
                        })

                        show_loading && wx.hideLoading();
                        this.callback_success && this.callback_success(data);
                    }, err => {
                        err;
                        show_loading && wx.hideLoading();
                        this.onCancel();
                    });
                },
                fail: err => {
                    show_loading && wx.hideLoading();
                    console.log(err);
                    this.onCancel();
                }
            });
        }
    }
})
